package org.footito.android.api;

import org.footito.android.data.database.ProviderAdapter;
import org.footito.android.tools.FootitoException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

/**
 * @author jdelrio
 * 
 */
public class CommentApiHandler extends DefaultHandler {
	private static final String TAG_TIMELINEELEMENT = "timelineElements";
	private static final String TAG_COMMENT = "comment";
	private static final String TAG_COMMENTID = "id";
	private static final String TAG_COMMENTIDPARENT = "idParent";
	private static final String TAG_COMMENTIDTEAM = "idTeam";

	public final static String URL_API = "http://api.footito.fr/comment/list";
	public final static String URL_API_PARAM_LIMIT = "limit";
	public final static String URL_API_PUBLISHED_AFTER = "published_after";

	private boolean inTimelineElement;
	private boolean inComment;
	private ProviderAdapter db;
	private String commentContent;
	private int commentId;
	private int commentIdTeam;
	private int commentIdEvent;

	/**
	 * 
	 */
	public CommentApiHandler(ProviderAdapter db) {
		this.db = db;
	}

	@Override
	public void startDocument() throws SAXException {
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (localName.equals(TAG_TIMELINEELEMENT)) {
			inTimelineElement = true;
		} else if (localName.equals(TAG_COMMENT)) {
			this.inComment = true;
			this.commentContent = "";
			this.commentIdEvent = Integer.parseInt(attributes.getValue(TAG_COMMENTIDPARENT));
			this.commentId = Integer.parseInt(attributes.getValue(TAG_COMMENTID));
			this.commentIdTeam = Integer.parseInt(attributes.getValue(TAG_COMMENTIDTEAM));
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (localName.equals(TAG_TIMELINEELEMENT)) {
			inTimelineElement = false;
		} else if (localName.equals(TAG_COMMENT)) {
			inComment = false;
			try {
				db.insertComment(commentId, commentIdEvent, commentContent, commentIdTeam);
			} catch (FootitoException e) {
				Log.e("Footito", "FootitoException: " + e.getMessage());
			}
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		if (inComment) {
			this.commentContent += new String(ch, start, length);
		}
	};
}
